const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = require('../config/database');

// 导入各个模型
const User = require('./User');
const Video = require('./Video');
const Category = require('./Category');
// 导入关联表
const Like = require('./Like');
const Favorate = require('./Favorate');
const UserCoinVideo = require('./UserCoinVideo');
// const UserCollectVideo = require('./UserCollectVideo');
const Comment = require('./Comment');
const UserFollow = require('./UserFollow')(sequelize); // 初始化UserFollow模型
const Message = require('./Message');
// const OperationLogs = require('./OperationLogs');
const VideoType = require('./VideoType');

// 定义关联关系 - 只保留基本关联，避免创建多余的表结构
// User 关联
User.hasMany(Video, { foreignKey: 'user_id', as: 'videos' });
User.hasMany(Comment, { foreignKey: 'user_id', as: 'comments' });

// Video 关联
Video.belongsTo(User, { foreignKey: 'user_id', as: 'creator' });
Video.hasMany(Comment, { foreignKey: 'video_id', as: 'comments' });

// Comment 关联
Comment.belongsTo(User, { foreignKey: 'user_id', as: 'commenter' });
Comment.belongsTo(Video, { foreignKey: 'video_id', as: 'commentedVideo' });
Comment.belongsTo(Comment, { foreignKey: 'parent_id', as: 'parentComment' });
Comment.hasMany(Comment, { foreignKey: 'parent_id', as: 'commentReplies' });

// UserFollow 关联
UserFollow.belongsTo(User, { foreignKey: 'follower_id', as: 'followerUser' });
UserFollow.belongsTo(User, { foreignKey: 'followed_id', as: 'followedUser' });
User.hasMany(UserFollow, { foreignKey: 'follower_id', as: 'following' });
User.hasMany(UserFollow, { foreignKey: 'followed_id', as: 'followers' });

// 导出所有模型
module.exports = {
  Sequelize,
  sequelize,
  User,
  Video,
  Category,
  Comment,
  UserFollow,
  Like,
  Favorate,
  UserCoinVideo,
  Message,
  VideoType
};

// 将模型挂载到全局对象，方便在其他地方使用
if (typeof global !== 'undefined') {
  global.models = module.exports;
}